package com.admin.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.admin.common.annotation.Log;
import com.admin.common.constant.CacheConstants;
import com.admin.common.core.controller.BaseController;
import com.admin.common.core.domain.R;
import com.admin.common.core.page.TableDataInfo;
import com.admin.common.enums.BusinessType;
import com.admin.common.utils.poi.ExcelUtil;
import com.admin.common.utils.redis.RedisUtils;
import com.admin.system.domain.SysLoginLog;
import com.admin.system.domain.vo.SysLoginLogQuery;
import com.admin.system.service.SysLoginLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 系统访问记录
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/log/login")
public class SysLoginlogController extends BaseController {

    private final SysLoginLogService logininforService;

    /**
     * 获取系统访问记录列表
     */
    @SaCheckPermission("system:loginlog:list")
    @PostMapping("/list")
    public TableDataInfo<SysLoginLog> list(@RequestBody SysLoginLogQuery logininfor) {
        return logininforService.selectPageLogininforList(logininfor);
    }

    /**
     * 导出系统访问记录列表
     */
    @Log(title = "登录日志", businessType = BusinessType.EXPORT)
    @SaCheckPermission("system:loginlog:export")
    @PostMapping("/export")
    public void export(@RequestBody SysLoginLogQuery logininfor, HttpServletResponse response) {
        List<SysLoginLog> list = logininforService.selectLogininforList(logininfor);
        ExcelUtil.exportExcel(list, "登录日志", SysLoginLog.class, response);
    }

    /**
     * 批量删除登录日志
     * @param ids 日志ids
     */
    @SaCheckPermission("system:loginlog:delete")
    @Log(title = "登录日志", businessType = BusinessType.DELETE)
    @PostMapping("/delete/{ids}")
    public R<Void> remove(@PathVariable Long[] ids) {
        return toAjax(logininforService.deleteLogininforByIds(ids));
    }

    /**
     * 清理系统访问记录
     */
    @SaCheckPermission("system:loginlog:delete")
    @Log(title = "登录日志", businessType = BusinessType.CLEAN)
    @PostMapping("/clean")
    public R<Void> clean() {
        logininforService.cleanLogininfor();
        return R.ok();
    }

    @SaCheckPermission("system:loginlog:unlock")
    @Log(title = "账户解锁", businessType = BusinessType.OTHER)
    @PostMapping("/unlock/{userName}")
    public R<Void> unlock(@PathVariable("userName") String userName) {
        String loginName = CacheConstants.PWD_ERR_CNT_KEY + userName;
        if (RedisUtils.hasKey(loginName)) {
            RedisUtils.deleteObject(loginName);
        }
        return R.ok();
    }

}
